package Week.w151;

import common.ListNode;
import org.junit.Test;

import java.util.*;

public class Solution3 {
    public ListNode removeZeroSumSublists1(ListNode head) {
        ListNode Head=new ListNode(0);
        Head.next=head;
        ListNode cur=Head;
        while(cur!=null){
            int sum=0;
            while(head!=null){
                sum+=head.val;
                if(sum==0){
                    cur.next=head.next;
                }
                head=head.next;
            }
            cur=cur.next;
            if(cur!=null)
                head=cur.next;
        }
        return Head.next;
    }


    public ListNode removeZeroSumSublists(ListNode head) {
        while(head!=null&&head.val==0){
            head=head.next;
        }
        if(head==null){
            return null;
        }
       ListNode cur=new ListNode(0);
       cur.next=head;
       int sumOut=head.val;
       while (head.next!=null){
           if(head.next.val==0){
               head.next=head.next.next;
               if(head.next==null){
                   break;
               }
               continue;
           }
           sumOut+=head.next.val;
           if(sumOut==0){
               cur.next=head.next.next;
               head=head.next;
           }
           ListNode inCur=new ListNode(0);
           if(head.next==null){
               break;
           }
           inCur.next=head.next;
           int sumIn=inCur.next.val;
           while (inCur.next.next!=null){
               sumIn+=inCur.next.next.val;
               if(sumIn==0){
                   inCur.next=inCur.next.next;
                   head.next=inCur.next.next;
               }
               if(inCur.next.next==null){
                   break;
               }
               inCur.next=inCur.next.next;
           }
           if(head.next==null){
               break;
           }
           head=head.next;
       }

        return cur.next;

    }

   @Test
    public void test(){
       ListNode l1=new ListNode(-1);
       ListNode l2=new ListNode(1);
       l1.next=l2;
       ListNode l3=new ListNode(0);
       l2.next=l3;
       ListNode l4=new ListNode(-1);
       l3.next=l4;
      /* ListNode l5=new ListNode(-2);
       l4.next=l5;*/
       ListNode result=removeZeroSumSublists(l1);
       System.out.println(result);


   }
}
